package com.unitd.base.frame.plugin.db.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.unitd.base.frame.plugin.db.datasource.aop.MultiSourceExAop;
import com.unitd.base.frame.plugin.db.datasource.context.DataSourceContext;
import com.unitd.base.frame.plugin.db.datasource.factory.AtomikosFactory;
import com.unitd.base.frame.plugin.db.datasource.properties.DruidProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 多数据源配置
 * 注:由于引入多数据源,所以让spring事务的aop要在多数据源切换aop的后面
 *
 * @author Hudan
 * @version 1.0
 * @filename DataSourceConfig.java
 * @copyright www.unitd.com
 * @date 2020-06-28
 */
@SpringBootConfiguration
public class DataSourceConfig {

    /**
     * 默认主数据源配置
     *
     * @return 数据源配置信息
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidProperties druidProperties() {
        return new DruidProperties();
    }

    /**
     * 主数据源实例
     *
     * @param druidProperties 数据源配置信息
     * @return 数据源实例
     */
    @Primary
    @Bean
    public DataSource dataSourcePrimary(@Qualifier("druidProperties") DruidProperties druidProperties) {
        return AtomikosFactory.create(DataSourceContext.MASTER_DATASOURCE_NAME, druidProperties);
    }

    /**
     * @return
     */
    @Bean(initMethod = "init")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        this.druidProperties().config(dataSource);
        return dataSource;
    }

    /**
     * 多数据源切换的aop
     *
     * @return 多数据源
     */
    @Bean
    public MultiSourceExAop multiSourceExAop() {
        return new MultiSourceExAop();
    }
}